package com.easy.frame.base.service.config;

import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 读写分离数据源配置
 *
 * @Author zzf
 * @Date 2020/5/24 002415:45
 */
@Configuration
public class DataSourceConfig {

    /**
     * 下面的配置解决批量操作的异常
     */
    @Bean(name = "wallConfig")
    WallConfig wallFilterConfig() {
        WallConfig wc = new WallConfig();
        wc.setMultiStatementAllow(true);
        wc.setNoneBaseStatementAllow(true);
        return wc;
    }

    @Bean(name = "wallFilter")
    @DependsOn("wallConfig")
    WallFilter wallFilter(WallConfig wallConfig) {
        WallFilter wfilter = new WallFilter();
        wfilter.setConfig(wallConfig);
        return wfilter;
    }


    /**
     * 设置seata数据源代理和事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier("masterSlaveDataSource") DataSource dataSource) {
        MasterSlaveDataSource masterSlaveDataSource = (MasterSlaveDataSource) dataSource;
        Map<String, DataSource> dataSourceMap = masterSlaveDataSource.getDataSourceMap();
        final String masterKey = "master";
        DataSource master = dataSourceMap.get(masterKey);
        DataSourceProxy sourceProxy = new DataSourceProxy(master);
        dataSourceMap.replace(masterKey, sourceProxy);
        return new DataSourceTransactionManager(dataSource);
    }

}
